package com.salim.leetcode.$56;

import java.util.ArrayList;
import java.util.List;

public class MergeIntervals {
    public int[][] merge(int[][] intervals) {
        if(intervals.length==0){
            return intervals;
        }

        List<Integer> result = new ArrayList<>();
        for(int i=0;i<intervals.length;i++){
            if(intervals[i][0]==-1 && intervals[i][1]==-2){
                continue;
            }
            boolean doChange = false;
            for(int j=i+1;j<intervals.length;j++){
                if(intervals[j][0]==-1 && intervals[j][1]==-2){
                    continue;
                }
                if(intervals[i][0]<=intervals[j][1] && intervals[i][1]>=intervals[j][0]){
                    doChange = true;
                    intervals[i][0] = Math.min(intervals[i][0],intervals[j][0]);
                    intervals[i][1] = Math.max(intervals[i][1],intervals[j][1]);
                    intervals[j][0] = -1;
                    intervals[j][1] = -2;
                }
            }
            if(doChange){
                i--;
            }else{
                result.add(intervals[i][0]);
                result.add(intervals[i][1]);
            }
        }
        int[][] resultArray = new int[result.size()/2][2];
        for(int i=0;i<resultArray.length;i++){
            resultArray[i][0] = result.get(i*2);
            resultArray[i][1] = result.get(i*2+1);
        }
        return resultArray;
    }

}
